<?php

namespace app\common\model\mysql;

use think\Model;

class Category extends Model
{
    protected $autoWriteTimestamp = true;

    public function getCategoryByName($name)
    {
        if (empty($name)) {
            return false;
        }
        $where = [
            'name' => $name,
        ];
        return $this->where($where)->find();
    }

    /**
     * @param $field
     * @return Category[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * User: xyb
     * Date: 2023/3/11 19:16
     */
    public function getNormalCategorys($field = "*")
    {
        $where = [
            'status' => config("status.mysql.table_normal"),
        ];
        $order = [
            'list_order' => 'desc',
            'id' => 'asc',
        ];
        return $this->where($where)
            ->field($field)
            ->order($order)
            ->select();
    }

    public function getList($where, $page = 10)
    {
        $order = [
            'list_order' => 'desc',
            'id' => 'asc',
        ];
        $result =  $this->where($where)
            ->where("status", '<>', config("status.mysql.table_delete"))
            ->order($order)
            ->paginate($page);
//        echo $this->getLastSql();exit();
        return $result;
    }


    public function updateById($id, $data)
    {
        $where = [
            'id' => $id,
        ];
        $data['update_time'] = time();
        return $this->where($where)->save($data);
    }

    public function updateByStatus($id, $data)
    {
        $where = [
            'id' => $id,
        ];
        $data['update_time'] = time();
        return $this->where($where)->save($data);

    }

    public function getChildCountInPids($condition)
    {
        $where[] = ['pid', 'in', $condition['pid']];
        $where[] = ['status', '<>', config("status.mysql.table_delete")];
        $res = $this->where($where)
            ->field('pid, count(*) as count')
            ->group('pid')
            ->select();
//        echo $this->getLastSql();
        return $res;
    }

    public function getTest($condition)
    {
        $where[] = ['id', 'in', $condition['pid']];
        $res = $this->where($where)
            ->field('pid')
            ->group('pid')
            ->select();
        echo $this->getLastSql();
        return $res;
    }

    public function getNormalByPid($pid, $field)
    {
        $where = [
            'pid' => $pid,
            'status' => config("status.mysql.table_normal")
        ];
        $order = [
            'list_order' => 'desc',
            'id' => 'desc'
        ];
        $result = $this->where($where)
            ->field($field)
            ->order($order)
            ->select();
        return $result;
    }

}